package deepbitview

import groovyx.net.http.HTTPBuilder
import org.apache.http.auth.AuthScope
import org.apache.http.auth.UsernamePasswordCredentials
import static groovyx.net.http.ContentType.URLENC
import sun.net.www.protocol.http.AuthCache
import org.apache.http.impl.auth.BasicScheme
import org.apache.http.protocol.BasicHttpContext
import org.apache.http.client.protocol.ClientContext
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
import java.text.SimpleDateFormat as SDF
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID
import groovyx.net.http.HttpURLClient
import org.apache.log4j.Logger
import org.apache.log4j.Level;

/**
 * simple utility to simplify JSON queries
 */
class JSONQueryUtil {

    /**
     * executes a query for the given url and the given path. You need to provide the parameters as a map
     * @param url
     * @param parameter
     * @param path
     * @return
     */
    public static executeQuery(def url, Map parameter, String path) {
        TrustManager.generateTrustedSSL()

        def http = new HTTPBuilder(url)

        def result = ""
        http.post(body: parameter, path: path, requestContentType: URLENC) { resp, json ->

            if (resp.statusLine.statusCode == 200) {
                result = json
            }
            else {
                result = false
            }

        }

        return result
    }

    /**
     * executes a query, which needs a basic http authentification
     * @param url
     * @param parameter
     * @param path
     * @return
     */
    public static executeQueryWithAuthentification(def url, Map parameter, def userName, def password,def path) {
        def result = ""

        def authSite = new HTTPBuilder('http://127.0.0.1:8332/',JSON)
        authSite.auth.basic userName, password

        authSite.get(path: path,
                query: [:]) { resp, json ->

            println resp.status

            json.each {  // iterate over JSON 'status' object in the response:
                println it
            }
        }


        return result
    }


}
